package com.example.ai.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.Date;

/**
 * 全局异常处理器，处理应用中的所有异常情况
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleGlobalException(Exception ex, WebRequest request) {
        ErrorDetails errorDetails = new ErrorDetails(
                new Date(),
                ex.getMessage(),
                request.getDescription(false),
                "INTERNAL_SERVER_ERROR"
        );
        return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    /**
     * 处理认证相关的异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> handleRuntimeException(RuntimeException ex, WebRequest request) {
        // 检查异常消息是否包含认证相关的关键词
        if (ex.getMessage().contains("未授权") || ex.getMessage().contains("授权")) {
            ErrorDetails errorDetails = new ErrorDetails(
                    new Date(),
                    ex.getMessage(),
                    request.getDescription(false),
                    "UNAUTHORIZED"
            );
            return new ResponseEntity<>(errorDetails, HttpStatus.UNAUTHORIZED);
        }
        
        // 其他运行时异常
        ErrorDetails errorDetails = new ErrorDetails(
                new Date(),
                ex.getMessage(),
                request.getDescription(false),
                "BAD_REQUEST"
        );
        return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
    }
    
    /**
     * 错误详情类，用于返回格式化的错误信息
     */
    public static class ErrorDetails {
        private Date timestamp;
        private String message;
        private String details;
        private String errorCode;
        
        public ErrorDetails(Date timestamp, String message, String details, String errorCode) {
            super();
            this.timestamp = timestamp;
            this.message = message;
            this.details = details;
            this.errorCode = errorCode;
        }
        
        // Getters
        public Date getTimestamp() {
            return timestamp;
        }
        
        public String getMessage() {
            return message;
        }
        
        public String getDetails() {
            return details;
        }
        
        public String getErrorCode() {
            return errorCode;
        }
    }
}